% author: Markus Scherer
% generates diltated image
% input:  in    ... image to filter
%         k     ... filter kernel
%         f     ... value that is assumed for "the world outside the borders of the image"
%         smode ... if 'full': image is enlarged according to filter
% output: filtered image
function out = mifilter(in, k, f, smode)
    if ~exist('smode','var')
        smode = 'same';
    end

    se = mistrel(k); % abuse strel as selection generator
    si = size(in);
   
    if strcmp(smode, 'full')
     tmp = zeros(si(1) + sum([abs(se.hu), abs(se.hd)]), si(2) + sum([abs(se.wr) + abs(se.wl)]));
     tmp(:,:) = f;
     tmp((1:si(1)) + abs(se.hd), (1:si(2)) + abs(se.wr)) = in;
     in = tmp;
     si = size(in);
    end 

    for i = 1:si(1)
      for j = 1:si(2)
        [iselv iselh] = genimgsel(se,i,j,si);
        [sselv sselh] = genstrelsel(se,i,j,si);
        ktmp = k(sselv, sselh);
        tmp = in(iselv, iselh);
        value = sum(sum(ktmp .* tmp));

        ktmp     = k;
        ktmp(sselv, sselh) = 0;
        tmp      = k;
        tmp(:,:) = f;
        value = value + sum(sum(ktmp .* tmp));

        out(i,j) = value;
    end
 end
